<template>
  <div class="login-container">
    <div class="login-form">
      <div class="logo-image">
        <img src="../assets/LoginImg/jng2.png" alt="登录左图">
      </div>
      <div class="logo-content">
        <div class="logo">
          <i class="el-icon-fish"></i>
          <h2 style="color: darkorange;">别看了空军佬，这里没鱼</h2>
          <p>一站式钓鱼助手系统</p>
        </div>
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"
              show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%" :loading="loading" @click="handleLogin">
              登录
            </el-button>
          </el-form-item>
          <el-form-item>
            <div style="display: flex; justify-content: space-between; width: 100%;">
              <el-button type="primary" style="flex: 1; margin-right: 10px;" :loading="registerLoading"
                @click="handleRegisterClick">
                {{ registerLoading ? '跳转中...' : '注册' }}
              </el-button>
              <el-button type="primary" style="flex: 1; margin-left: 10px;" :loading="guestLoading"
                @click="handleGuestClick">
                {{ guestLoading ? '跳转中...' : '游客进入' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" style="width: 100%;" :loading="adminLoading"
              @click="handleAdminClick">
              {{ adminLoading ? '跳转中...' : '管理员登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        <div class="login-tips">
          <p>此系统最终解释权归作者-赵涛-所有</p>
          <p>Copyright 2025 ZhaoTao. All rights reserved.</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api'
import { useAuthStore } from '@/stores/authStore'

export default {
  name: 'UserLoginView',
  setup() {
    const router = useRouter()
    const auth = useAuthStore()
    const loginFormRef = ref()
    const loading = ref(false)
    const registerLoading = ref(false)
    const guestLoading = ref(false)
    const adminLoading = ref(false)

    const handleRegisterClick = () => {
      if (registerLoading.value || guestLoading.value || adminLoading.value) return
      registerLoading.value = true
      setTimeout(() => {
        router.push('/register')
      }, 1000)
    }

    const handleGuestClick = () => {
      if (registerLoading.value || guestLoading.value || adminLoading.value) return
      guestLoading.value = true
      setTimeout(() => {
        router.push('/')
      }, 1000)
    }

    const handleAdminClick = () => {
      if (registerLoading.value || guestLoading.value || adminLoading.value) return
      adminLoading.value = true
      // 清除可能存在的管理员token，避免重定向循环
      auth.logoutAdmin()
      setTimeout(() => {
        router.push('/admin/login')
      }, 500)
    }

    const loginForm = reactive({
      username: '',
      password: ''
    })

    // 验证逻辑
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '用户名长度必须在 5 到 16 个字符之间', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码长度必须在 5 到 16 个字符之间', trigger: 'blur' }
      ]
    }

    const handleLogin = async () => {
      loginFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            // 使用统一API管理
            const response = await userAPI.login({
              username: loginForm.username,
              password: loginForm.password
            })
            
            // 调试：查看后端返回的完整内容
            console.log('后端返回的完整响应:', response)
            console.log('response.data:', response.data)
            
            // 检查登录是否成功
            if (response.code === 0) {
              // 登录成功：存储Token和用户信息
              if (response.data && response.data.token) {
                // 详细调试后端返回的数据
                console.log('后端返回的完整数据:', response.data)
                console.log('response.data.userInfo:', response.data.userInfo)
                console.log('response.data.userId:', response.data.userId)
                console.log('response.data.username:', response.data.username)
                
                // 存储用户信息 - 支持多种数据格式
                let userInfo = null
                
                if (response.data.userInfo) {
                  // 如果后端返回完整的用户信息对象
                  userInfo = response.data.userInfo
                  console.log('使用后端返回的userInfo:', userInfo)
                } else if (response.data.userId) {
                  // 如果后端只返回userId，创建用户信息对象
                  userInfo = {
                    userId: response.data.userId,
                    username: response.data.username || loginForm.username,
                    nickName: response.data.nickName || response.data.username || loginForm.username
                  }
                  console.log('创建的用户信息对象:', userInfo)
                } else {
                  // 如果后端没有返回用户ID，使用默认值
                  userInfo = {
                    userId: 1, // 临时默认用户ID
                    username: loginForm.username,
                    nickName: loginForm.username
                  }
                  console.log('使用默认用户信息:', userInfo)
                }
                
                // 关键修复：使用authStore统一管理token和用户信息
                auth.setUserToken(response.data.token)
                auth.setUserInfo(userInfo)
                
                console.log('登录成功，存储的Token:', response.data.token)
                console.log('存储的用户信息:', userInfo)
                ElMessage.success('登录成功')
                
                // 延迟跳转，确保authStore状态已更新
                // 使用nextTick或setTimeout确保Vue响应式系统已更新
                setTimeout(() => {
                  // 根据redirect参数跳转（从购物车跳转登录则返回购物车）
                  const redirect = router.currentRoute.value.query.redirect || '/'
                  router.push(redirect)
                }, 100)
              } else {
                throw new Error('后端返回数据格式错误：缺少token')
              }
            } else {
              // 登录失败：显示后端返回的错误信息
              let errorMessage = response.message || '登录失败'
              
              // 将技术性错误转换为用户友好的提示
              if (errorMessage.includes('dbUser') && errorMessage.includes('null')) {
                errorMessage = '用户名不存在'
              } else if (errorMessage.includes('密码错误')) {
                errorMessage = '密码错误'
              } else if (errorMessage.includes('用户不存在')) {
                errorMessage = '用户名不存在'
              }
              
              throw new Error(errorMessage)
            }
          } catch (error) {
            // 错误处理（拦截器已统一处理，此处可简化）
            ElMessage.error(error.message || '登录失败，请检查账号密码')
          } finally {
            loading.value = false
          }
        }
      })
    }

    return {
      loginFormRef,
      loginForm,
      rules,
      loading,
      handleLogin,
      router,
      registerLoading,
      guestLoading,
      adminLoading,
      handleRegisterClick,
      handleGuestClick,
      handleAdminClick
    }
  }
}
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: rgb(202, 253, 255);
  background-size: cover;
  background-position: center center;
}
.login-form {
  width: 800px;
  padding: 0;
  background: linear-gradient(135deg, #eafff1 0%, #efffc9 100%);
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2),
    0 5px 15px rgba(0, 0, 0, 0.15),
    0 0 0 1px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  display: flex;
  align-items: stretch;
  height: auto;
}
.logo-image {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}
.logo-image img {
  max-width: 100%;
  max-height: 100%;
}
.logo-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}
.logo {
  text-align: center;
  margin-bottom: 30px;
}
.logo i {
  font-size: 48px;
  color: #409EFF;
}
.logo h2 {
  margin: 10px 0 5px;
  color: #304156;
}
.logo p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}
.login-tips {
  margin-top: 20px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
.login-tips p {
  margin: 5px 0;
}
/* 响应式设计 */
@media (max-width: 768px) {
  .login-form {
    width: 90%;
  }
  .logo-wrapper {
    flex-direction: column;
    height: auto;
  }
  .logo-image {
    height: 300px;
  }
}
</style>